#include <iostream>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include "httpd.h"

using namespace std;

void usage(char *argv0) // 说明用法
{
	cerr << "Usage: " << argv0 << " listen_port docroot_dir nopool" << endl
		 << "or" << endl
		 << "Usage: " << argv0 << " listen_port docroot_dir pool N" << endl;

	// Usage: ./httpd listen_port docroot_dir nopool
	// or
	// Usage: ./httpd listen_port docroot_dir pool N
}

// argv[1]--端口号,argv[2]--网页的根目录,argv[3]--线程的数量
int main(int argc, char *argv[])
{
	cout << "argc: " << argc << endl;
	if (argc != 4 && argc != 5)
	{
		usage(argv[0]);
		return 1;
	}

	long int port = strtol(argv[1], NULL, 10);

	if (errno == EINVAL || errno == ERANGE)
	{
		usage(argv[0]);
		return 2;
	}

	if (port <= 0 || port > USHRT_MAX)
	{
		cerr << "Invalid port: " << port << endl;
		return 3;
	}

	string doc_root = argv[2];
	string newStr;
	int pool_num = 0;
	if (argc == 5)
		pool_num = atoi(argv[4]);
	if (doc_root[doc_root.length() - 1] != '/')
	{
		doc_root.push_back('/');
	}

	start_httpd(port, doc_root, pool_num);

	return 0;
}
